<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <div>
            <span>全选:</span>
            <input type="checkbox" v-model="selectAll" @click="allSelected" />
            <button @click="allSelected">反选</button>
            <ul>
                <li v-for="(item,index) in arr" :key="index">
                    <!-- 此处的v-model的作用是将item.checked的值绑定到input的checked属性上 -->
                    <input type="checkbox" v-model="item.checked" />
                    <span>{{item.name}}</span>
                </li>
            </ul>
        </div>
    </div>
    <script src="./vue.js"></script>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                selectAll: false,
                arr: [
                    {
                        name: "猪八戒",
                        checked: false,
                    },
                    {
                        name: "孙悟空",
                        checked: false,
                    },
                    {
                        name: "唐僧",
                        checked: true,
                    },
                    {
                        name: "白龙马",
                        checked: false,
                    },
                ],
            },
            methods: {
                // 全选
                allSelected() {
                    console.log(this.selectAll = !this.selectAll);
                    this.arr.forEach(item => { item.checked = this.selectAll })
                },
                // 小选
                smallSelected() {
                    this.arr.forEach(item => { item.checked = !item.checked })
                    this.updateSelect()
                },
                // 更新全选按钮的状态
                updateSelect() {
                    // 判断是否全选
                    this.selectAll = this.arr.every(item => item.checked)
                },

            },
            watch: {
                // 监听 arr 数组的变化，以更新全选按钮的状态
                // arr表示数据属性名
                arr: {
                    handler() {
                        this.updateSelect();
                    },
                    deep: true
                }
            }
        })
    </script>


</body>

</html>